/* FILE : helper manager HM.c */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

#include <standard_im.h>

#include "HM.h"

static void run_ui(char *);
static int is_ui_available(char *);
static void on_child_exit(int);

static pid_t child = -1;

int
HM_load_ui(char *ui_path)
{
	child = fork();

	if (!is_ui_available(ui_path)) {
#if DEBUG
		fprintf(stderr, "XAUX : cannot find default ui\n");
#endif
		return 0;
	}

	if (child < 0) {
#if DEBUG
		fprintf(stderr, "XAUX : helper manager cannot fork for default ui\n");
#endif
		return 0;
	} else if (child == 0) {
		run_ui(ui_path);
		exit(1);
	} else {
		signal(SIGCHLD, on_child_exit);
	}
	return 1;
}

void
HM_stop_ui(char *ui_path)
{
	kill(child, SIGTERM);
}

static void
run_ui(char *ui_path)
{
	char *argv[2];

	argv[0] = ui_path;
	argv[1] = NULL;
	execv(ui_path, argv);
}

static int
is_ui_available(char *ui_path)
{
	if (access(ui_path, X_OK) == -1)
		return 0;
	else
		return 1;
}

static void
on_child_exit(int signo)
{
	waitpid(child, NULL, WNOHANG);
	child = -1;
}
